package xin.core.jwt;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import xin.common.utils.Roll;
import xin.core.AppConstant;

/**
 * <pre>
 * 自定义 MD5 PasswordEncoder
 * </pre>
 *
 * @author lixin
 * @version 1.0
 * @since 2017/11/25 17:38
 */
@Slf4j
public class MD5PasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence charSequence) {
        String salt  = Roll.string(32);
        log.info(" encod esalt : " + salt);
        String hash = salt + DigestUtils.sha512Hex(salt + charSequence);
        log.info(" encode hash : " + hash);
        return hash;
    }

    @Override
    public boolean matches(CharSequence planText, String hash) {

        log.info(" matches planText : " + planText);
        log.info(" matches hash : " + hash);
        String salt  = hash.substring(0,32);
        log.info(" matches salt : " + salt);
        String realHash  = hash.substring(32);
        log.info("matches realHash : " + realHash);
        return realHash.equals(DigestUtils.sha512Hex(salt + planText));
    }

    public static void main(String args [] ){
        MD5PasswordEncoder encoder = new MD5PasswordEncoder();
        log.info("result :{},",encoder.matches(AppConstant.DEFAULT_PASSWD,encoder.encode(AppConstant.DEFAULT_PASSWD)));
    }
}